using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace CodeFactory.Library.Config
{
    public static class ConfigManager
    {
        private static string currentPath;
        private static string configFile;

        private static SystemInfo systemInfo;

        private static object lockObj = new object();

        static ConfigManager()
        {
            try
            {
                currentPath = System.Environment.CurrentDirectory;
                configFile = string.Format("{0}\\System.config", currentPath);
                lock (lockObj)
                {
                    StreamReader sr = new StreamReader(configFile);
                    XmlSerializer xs = new XmlSerializer(typeof(SystemInfo));
                    systemInfo = xs.Deserialize(sr) as SystemInfo;
                    sr.Close();
                }
                if (systemInfo == null)
                {
                    LibraryMessageBox.ShowErrorAndExit("LanguageManager Initialization Error", "Can't load system infomation from " + configFile);
                }
            }
            catch (Exception e)
            {
                LibraryMessageBox.ShowErrorAndExit("LanguageManager Initialization Error", e.Message);
            }
        }

        public static void InitNewConfig()
        {
            SaveConfig(new SystemInfo());
        }

        public static void SaveConfig(SystemInfo info)
        {
            lock (lockObj)
            {
                StreamWriter sw = new StreamWriter(configFile);
                XmlSerializer xs = new XmlSerializer(typeof(SystemInfo));
                xs.Serialize(sw, info);
                sw.Close();
            }
        }

        public static string CurrentPath
        {
            get { return currentPath; }
        }

        public static string ConfigFile
        {
            get { return configFile; }
        }

        public static SystemInfo Info
        {
            get { return systemInfo; }
        }
    }
}
